<?php
// Jaiku2Twitter
// Post your Jaiku messages automatically to Twitter

// READ README.TXT FIRST!

/////////////////////////////////////////////////////////////////////////////////

function post_to_twitter($username,$password,$message) {

    $host = "http://twitter.com/statuses/update.xml?source=jaiku2twitter&status=".urlencode(stripslashes(urldecode($message)));

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $host);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_POST, 1);

    $result = curl_exec($ch);
    $array = curl_getinfo($ch);
    curl_close($ch);

    if($array['http_code'] == "200") {
        echo "Posted";
    } else {
        echo "Error :(";
    }

}

// Not needed if you have PHP5, but well... sue me
function read_file($myFile) {
	$fh = fopen($myFile, 'r');
	$theData = fread($fh, 1024);
	fclose($fh);
	return $theData;
}

function write_file($myFile, $stringData) {
	$fh = fopen($myFile, 'w') or die("can't open file");
	fwrite($fh, $stringData);
	fclose($fh);
}

// Check if it's a presence message, not a feed item, comment or channel message
function is_tweet($item) {
	if(eregi('/'.JAIKU_USERNAME.'\.jaiku\.com/', $item['link']) && !eregi('/Comment from/', $item['title'])) {
		return true;
	} else {
		return false;
	}
}

require("config.inc.php");

mysql_connect(DB_HOST, DB_USER, DB_PASS) or die ('Error connecting to MySQL');
mysql_select_db(DB_NAME);

$result = mysql_query("SELECT id FROM jaiku2twitter");
if(mysql_num_rows($result) == 0) {
	$dont = 1;
}


require('lastRSS.php');
$lastRSS = new lastRSS; 
$lastRSS->cache_time = 0;

$endmsg = '';

$rss = $lastRSS->get("http://".JAIKU_USERNAME.".jaiku.com/feed/rss?user=".JAIKU_USERNAME."&personal_key=".JAIKU_PERSONAL_KEY);

foreach($rss['items'] as $item) {
	if(is_tweet($item)) {
		$result = mysql_query("SELECT id FROM jaiku2twitter WHERE url='" . $item['link'] . "'");
		if(mysql_num_rows($result) == 0) {
			if($dont == 1) {
				$action = "Tested";
				$endmsg = "You're now ready! The next time you run this script, we'll post everything to Twitter immediately.";
			} else {
				post_to_twitter(TWITTER_USERNAME,TWITTER_PASSWORD,$item['title']);
				$action = "";
				$endmsg = "Done!";
			}
			echo "<p>".$action.":</p> <blockquote>" . $item['title'] . "</blockquote>";
			mysql_query("INSERT INTO jaiku2twitter(url, created_at) VALUES('" . $item['link'] . "', NOW())");
		} 		
	}
}
print $endmsg;
?>